//
//  WNLibraryAllVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/8/30.
//

import UIKit

class WNLibraryAllVC: WNBaseVC {
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: WNNotiName.collectNoti, object: nil)
    }
        
    lazy var libColView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = (ScreenW-scaleWidth(100)*3-42)*0.5
        layout.itemSize = CGSize(width: scaleWidth(100), height: scaleWidth(144)+42)
        layout.sectionInset = .init(top: 18, left: 20, bottom: 0, right: 20)
        let col = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        col.showsVerticalScrollIndicator = false
        col.showsHorizontalScrollIndicator = false
        col.backgroundColor = .white
        col.delegate = self
        col.dataSource = self
        col.register(LibColCell.self, forCellWithReuseIdentifier: LibColCell.identifier)
        col.ly_emptyView = WNEmptyView.wn_loadStyle(descStr: .library, imageStr: .library, tapBlock: { [weak self] in
            col.mj_header?.beginRefreshing()
        })
        col.isHidden = true
        return col
    }()
    
    lazy var deleteBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = .white
        btn.setTitle("Delete", for: .normal)
        btn.setTitle("Delete", for: .selected)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 16)
        btn.setTitleColor(.init(named: "gray_999999"), for: .normal)
        btn.setTitleColor(.init(named: "red_FE95B4"), for: .selected)
        btn.titleEdgeInsets = .init(top: 0, left: 0, bottom: TabBarMargin, right: 0)
        btn.rx.tap.bind { [weak self] in
            guard btn.isSelected else {
                return
            }
            showSpringType(.deleteViewedBook)
            WNSpringView.shared.isRightClosure = { isRight in
                if isRight {
                    self?.deleteColRequest()
                }
            }
        }.disposed(by: rx.disposeBag)
        btn.isHidden = true
        return btn
    }()
    
    var libArr = [BookDetailModel]()
    
    var selIndexArr = [Int]()
    
    var isEdit = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        view.addSubview(libColView)
        view.addSubview(deleteBtn)
        libColView.snp.makeConstraints { make in
            make.top.equalTo(NaviTotalHeight)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarMargin)
        }
        deleteBtn.snp.makeConstraints { make in
            make.left.bottom.right.equalTo(0)
            make.height.equalTo(0)
        }
        deleteBtn.wn_cornerWithBorder(0, 0, .white, 1, .init(white: 0, alpha: 0.1), .init(width: 0, height: 1), 5)
        deleteBtn.layer.masksToBounds = false
    }
    
    override func dataConfig() {
        pageName = "Library"
        navView.titleName = "Library"
        navView.rightBtnImge = "book_more"
        navView.rightClosure = { [weak self] in
            self?.showLibEdit()
        }
        listSettingRefresh()
        getLibRequest()
    }
    
    override func handleNoti() {
        NotificationCenter.default.addObserver(forName: WNNotiName.collectNoti, object: nil, queue: nil) { [weak self] not in
            if let favorite = not.userInfo?["favorite"] as? Bool, let bookId = not.userInfo?["bookId"] as? String {
                if favorite {
                    self?.libColView.mj_header?.beginRefreshing()
                }else {
                    if let arr = self?.libArr, arr.first(where: {$0.bookId == bookId }) != nil {
                        var item = 0
                        for (i, v) in arr.enumerated() {
                            if v.bookId == bookId {
                                item = i
                            }
                        }
                        self?.libArr.remove(at: item)
                        self?.libColView.reloadData()
                    }
                }
            }
        }
    }
}

extension WNLibraryAllVC {
    
    func showLibEdit() {
        if !isEdit {
            guard libArr.count > 0 else { return }
        }
        isEdit = !isEdit
        libColView.backgroundColor = isEdit ? .init(named: "white_F7F7F7") : .white
        deleteBtn.isHidden = !isEdit
        deleteBtn.snp.updateConstraints { make in
            make.height.equalTo(isEdit ? TabBarTotalHeight : 0)
        }
        if !isEdit {
            for i in 0..<libArr.count {
                libArr[i].isSel = false
            }
            deleteBtn.isSelected = false
        }
        libColView.reloadData()
        view.layoutIfNeeded()
    }
    
    func handleDeleteBtn() {
        let count = libArr.filter({$0.isSel}).count
        if count > 0 {
            deleteBtn.isSelected = true
            deleteBtn.setTitle(("Delete(\(count))"), for: .selected)
        }else {
            deleteBtn.isSelected = false
        }
    }
    
    func deleteItems() {
        selIndexArr.removeAll()
        var bookIds = [String]()
        for i in 0..<libArr.count {
            if libArr[i].isSel == true {
                selIndexArr.append(i)
                bookIds.append(libArr[i].bookId ?? "")
            }
        }
        if selIndexArr.count != 0 {
            libArr.removeAt(indexes: selIndexArr)
            libColView.reloadData()
        }
        NotificationCenter.default.post(name: WNNotiName.collectArrNoti, object: self, userInfo: ["bookIds": bookIds])
        showLibEdit()
    }
}

extension WNLibraryAllVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        libArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LibColCell.identifier, for: indexPath) as! LibColCell
        cell.isEdit = isEdit
        cell.model = libArr[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if isEdit {
            libArr[indexPath.item].isSel = !libArr[indexPath.item].isSel
            libColView.reloadItems(at: [indexPath])
            handleDeleteBtn()
        }else {
            wn_pushBookVC(libArr[indexPath.item].bookId ?? "")
        }
    }
}

extension WNLibraryAllVC {
    
    func listSettingRefresh() {
        libColView.mj_header = wn_refreshHeader(completion: { [weak self] in
            if (self?.isEdit ?? true) {
                self?.libColView.mj_header?.endRefreshing()
                return
            }
            self?.page = 1
            self?.hasPage = false
            self?.getLibRequest()
        })
        
        libColView.mj_footer = wn_refreshFooter(completion: { [weak self] in
            if (self?.isEdit ?? true) {
                self?.libColView.mj_footer?.endRefreshing()
                return
            }
            if self?.page == 1 && (self?.libArr.count ?? 0) == 0 {
                self?.libColView.mj_footer?.endRefreshing()
                return
            }
            if self?.hasPage == true {
                self?.page += 1
                self?.getLibRequest()
            }else {
                self?.libColView.mj_footer?.endRefreshingWithNoMoreData()
            }
        })
    }
}

extension WNLibraryAllVC {
    
    func getLibRequest() {
        provider_setting.rx.request(.collectList(page, 18))
            .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                self?.libColView.isHidden = false
                self?.libColView.ly_emptyView.imageStr = EmptyImage.library.rawValue
                self?.libColView.ly_emptyView.detailStr = EmptyDesc.library.rawValue
                self?.libColView.ly_emptyView.btnTitleStr = ""
                guard model.code == 0 else {
                    if (self?.isFirst ?? true) {
                        self?.libColView.ly_emptyView.imageStr = EmptyImage.serverBad.rawValue
                        self?.libColView.ly_emptyView.detailStr = EmptyDesc.serverBad.rawValue
                        self?.libColView.ly_emptyView.btnTitleStr = "Click Refresh"
                    }else {
                        self?.wn_toast(model.msg ?? "")
                    }
                    self?.libColView.mj_header?.endRefreshing()
                    self?.libColView.mj_footer?.endRefreshing()
                    self?.isFirst = false
                    return
                }
                if self?.page == 1 {
                    self?.libArr.removeAll()
                    self?.libColView.mj_footer?.resetNoMoreData()
                }
                if let arr = model.data {
                    self?.hasPage = arr.count > 17
                    self?.libArr += arr
                }else {
                    self?.libColView.mj_footer?.endRefreshingWithNoMoreData()
                }
                self?.libColView.reloadData()
                self?.libColView.mj_header?.endRefreshing()
                self?.libColView.mj_footer?.endRefreshing()
                self?.isFirst = false
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
                self?.libColView.ly_emptyView.imageStr = EmptyImage.netWork.rawValue
                self?.libColView.ly_emptyView.detailStr = EmptyDesc.netWork.rawValue
                self?.libColView.ly_emptyView.btnTitleStr = "Click Refresh"
                self?.libColView.mj_header?.endRefreshing()
                self?.libColView.mj_footer?.endRefreshing()
                self?.libColView.isHidden = false
            }).disposed(by: rx.disposeBag)
    }
    
    func deleteColRequest() {
        var bookIds = [String]()
        for i in 0..<libArr.count {
            if libArr[i].isSel == true {
                bookIds.append(libArr[i].bookId ?? "")
            }
        }
        guard bookIds.count > 0 else { return }
        provider_setting.rx.request(.collectDelete(bookIds.joined(separator: ",")))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if model.data != nil {
                    self?.wn_toast("You have removed these books from your Library")
                    self?.deleteItems()
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
}
